import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import * as dotenv from 'dotenv';
import { CatsModule } from './cats/cats.module';
import { UsersModule } from './users/users.module';
import { LogsModule } from './logs/logs.module';
import * as Joi from 'joi';
import { ConfigEnum } from './enum/config.enum';

const envFilePath = `.env.${process.env.NODE_ENV || 'development'}`;

@Module({
  imports: [
    // dotenv,
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath,
      //   expandVariables: true,
      //   envFilePath: `${process.env.NODE_ENV || 'development'}.env`,
      //   load: loadConfig,
      // 参考网址：joi.dev/api/
      load: [() => dotenv.config({ path: '.env' })],
      validationSchema: Joi.object({
        NODE_ENV: Joi.string()
          .valid('development', 'production', 'test', 'provision')
          .default('development'),
        DB_PORT: Joi.number().default(3306),
        DB_HOST: Joi.string().ip(),
        DB_TYPE: Joi.string().valid('mysql', 'postgres', 'mariadb'),
        DB_DATABASE: Joi.string().required(),
        DB_USER: Joi.string().required(),
        DB_PASSWORD: Joi.string().required(),
        DB_SYNC: Joi.boolean().default(false),
      }),
    }),
    // TypeOrmModule.forRoot({
    //   type: 'mysql',
    //   host: 'localhost',
    //   port: 3306,
    //   username: 'root',
    //   password: 'root',
    //   database: 'nestjs',
    //   logging: false,
    //   entities: [__dirname + '/**/*.entity{.ts,.js}'],
    //   synchronize: true, // 在生产环境中应禁用
    //   autoLoadEntities: true, // 自动加载实体类
    // }),
    // 异步配置
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) =>
        ({
          type: configService.get(ConfigEnum.DB_TYPE),
          host: configService.get(ConfigEnum.DB_HOST),
          port: configService.get(ConfigEnum.DB_PORT),
          username: configService.get(ConfigEnum.DB_USER),
          password: configService.get(ConfigEnum.DB_PASSWORD),
          database: configService.get(ConfigEnum.DB_DATABASE),
          entities: [__dirname + '/**/*.entity{.ts,.js}'],
          autoLoadEntities: true,
          synchronize: configService.get(ConfigEnum.DB_DATABASE),
          // logging: ['error'],
          logging: false, // 集成第三方日志
          // logging: process.env.NODE_ENV === 'development', // 打印sql语句
        }) as TypeOrmModuleOptions,
    }),
    UsersModule,
    CatsModule,
    LogsModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }
